import jira
import allure
from datetime import datetime


def mark_description(desc):
    """更健壮描述装饰器实现"""

    def decorator(func):
        # 保留原始函数信息
        func.__allure_description__ = desc

        # 添加动态描述逻辑
        def wrapper(*args, **kwargs):
            try:
                # 添加描述和链接
                allure.dynamic.description(desc)
                allure.dynamic.link("https://docs.example.com", name="功能文档")

                # 添加模块信息
                module_name = func.__module__.split('.')[-1]
                allure.dynamic.label("module", module_name)

                return func(*args, **kwargs)
            except Exception as e:
                # 异常时添加错误信息
                allure.dynamic.description(f"描述设置失败: {str(e)}\n{desc}")
                return func(*args, **kwargs)

        # 保留原始函数名和文档
        wrapper.__name__ = func.__name__
        wrapper.__doc__ = func.__doc__
        return wrapper

    return decorator


def capture_screenshot_on_failure():
    """失败时自动截图的装饰器"""

    def decorator(func):
        def wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except Exception as e:
                # 获取页面对象
                if 'page' in kwargs:
                    page = kwargs['page']
                    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                    filename = f"{func.__name__}_{timestamp}.png"
                    page.screenshot(path=filename)
                    allure.attach.file(filename, name="失败截图")
                raise e

        return wrapper

    return decorator


def link_jira(jira_id):
    """自动关联JIRA问题的装饰器"""

    def decorator(func):
        def wrapper(*args, **kwargs):
            # 添加JIRA链接
            url = f"https://jira.example.com/browse/{jira_id}"
            allure.dynamic.link(url, name=f"JIRA:{jira_id}")

            # 自动设置测试负责人
            owner = jira.get_assignee(jira_id)
            allure.dynamic.label("owner", owner)

            return func(*args, **kwargs)

        return wrapper

    return decorator